<?php

namespace App\Http\Controllers;

use App\Models\City;
use App\Models\CityBusiness;
use App\Models\Industry;
use App\Models\Shop;
use App\Models\Tuan;
use App\Models\TuanInfo;
use Exception;
use Illuminate\Http\Request;

/**
 * 搜索控制器
 */
class SearchController extends Controller
{
    /**
     * 搜索结果
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function search_result(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $title  = $request->get('title');
            $cityID = $request->get('city_id'); //当前城市id

            $shops = Shop::where('shop_name', 'like', '%' . $title . '%')
                ->where(['closed' => 1, 'audit' => 1, 'city_id' => $cityID])
                ->where(function ($query) use ($request) {
                    //全部分类
                    $cate_id  = $request->get('cate_id'); //分类id
                    $industry = Industry::where(['industryID' => $cate_id])->first();
                    if ($industry && $industry->type == 1) {
                        $query->where('cate_id', $cate_id);
                    } else if ($industry && $industry->type == 2) {
                        //二级分类
                        $industryID = $industry->PID;
                        $query->where('cate_id', $industryID);
                    } else {}
                })
                ->where(function ($query) use ($request) {
                    $area_id = $request->get('area_id');
                    $city    = City::where(['cityID' => $area_id])->first();
                    if (count($city) > 0 && $city->type == 4) {
                        $query->where('area_id', $area_id);
                    }
                })
                ->where(function ($query) use ($request) {
                    $business_id = $request->get('business_id');
                    $business    = CityBusiness::where(['id' => $business_id])->first();
                    if (count($business) > 0) {
                        $query->where('business_id', $business_id);
                    }
                })
                ->where(function ($query) use ($request) {
                    //智能排序（人气，推荐，距离）
                    if ($request->has('order_by')) {
                        $order_by = $request->get('order_by');
                        switch ($order_by) {
                            case 1: //人气
                                $query->orderBy('fans_num', 'desc'); //粉丝数量
                                break;
                            case 2: //推荐
                                $query->orderBy('sales', 'desc'); //销量
                                break;
                        }
                    }
                })->paginate(10);

            //处理数据
            foreach ($shops as $key => $value) {
                $data[$key]['shop_id']       = $value->shop_id;
                $data[$key]['shop_name']     = $value->shop_name;
                $data[$key]['logo']          = $value->logo; //店铺首图
                $data[$key]['average_price'] = sprintf('%.2f', $value->average_price); //人均价
                $data[$key]['star']          = $value->score_num > 0 ? intval(($value->score / $value->score_num) * 10) / 10 : 0; //评分
                $data[$key]['industry']      = $value->industry->industries()->pluck('name'); //店铺标签
                $data[$key]['pay_bills']     = $value->tuan_order()->where('pay_status', 2)->count(); //买单人数
                $data[$key]['is_integral']   = $value->is_integral; //是否开启积分抵扣

                //是否有在线团购
                $data[$key]['tuan'] = null;

                $tuans     = Tuan::where(['shop_id' => $value->shop_id, 'type' => 1])->pluck('tuan_id');
                $tuan_info = TuanInfo::where(['status' => 1, 'closed' => 1, 'audit' => 1])
                    ->whereIn('tuan_id', $tuans)->first();
                if ($tuan_info) {
                    $data[$key]['tuan'] = $tuan_info->title;
                }
                //是否有买单优惠
                $data[$key]['discount'] = null;
                if (count($value->shop_youhui) > 0) {
                    $data[$key]['discount'] = $value->shop_youhui->discount;
                }
                //是否有优惠券
                $data[$key]['voucher'] = null;

                $vouchers = Tuan::where(['shop_id' => $value->shop_id, 'type' => 2])->pluck('tuan_id');
                $tuanInfo = TuanInfo::where(['status' => 1, 'closed' => 1, 'audit' => 1])
                    ->whereIn('tuan_id', $vouchers)->first();
                if ($tuanInfo) {
                    $data[$key]['voucher'] = $tuanInfo->title;
                }
            }
            $status = 1;
            $msg    = '搜索成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 二级页面（点击分类进入）
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function second_page(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $cate_id = $request->get('cate_id'); //分类id
            if (empty($cate_id)) {
                throw new Exception('缺少参数');
            }
            //DB::connection()->enableQueryLog();
            //查询满足条件的商铺ID
            $shops = Shop::where(['closed' => 1, 'audit' => 1])
                ->where(function ($query) use ($cate_id) {
                    //判断是一级分类还是二级分类
                    $industry = Industry::where(['industryID' => $cate_id])->first();
                    if (count($industry) == 0) {
                        throw new Exception('参数错误');
                    }
                    if ($industry->type == 1) {
                        $query->where('cate_id', $cate_id);
                    } else if ($industry->type == 2) {
                        //二级分类
                        $industryID = $industry->PID;
                        $query->where('cate_id', $industryID);
                    } else {}
                })
                ->where(function ($query) use ($request) {
                    $cityID = $request->get('city_id');
                    $city   = City::where(['cityID' => $cityID])->first();
                    if (count($city) > 0 && $city->type == 3) {
                        $query->where('city_id', $cityID);
                    }
                })
                ->where(function ($query) use ($request) {
                    $area_id = $request->get('area_id');
                    $city    = City::where(['cityID' => $area_id])->first();
                    if (count($city) > 0 && $city->type == 4) {
                        $query->where('area_id', $area_id);
                    }
                })
                ->where(function ($query) use ($request) {
                    $business_id = $request->get('business_id');
                    $business    = CityBusiness::where(['id' => $business_id])->first();
                    if (count($business) > 0) {
                        $query->where('business_id', $business_id);
                    }
                })
                ->where(function ($query) use ($request) {
                    $orderby = $request->get('orderby'); //1人气 2 推荐
                    if ($orderby == 1) {
                        $query->orderBy('fans_num', 'desc');
                    } else if ($orderby == 2) {
                        $query->orderByRaw('score/score_num  desc'); //评分排序
                    } else {}
                })
                ->paginate(10);
            //dump(DB::getQueryLog());
            /*
            //先查广告
            $ads = Ad::where(['site_id' => 3, 'city_id' => $cityID, 'closed' => 1])
            ->where('bg_date', '<', time())->where('end_date', '>', time())
            ->orderBy('orderby')
            ->pluck('goal')
            ->toArray();

            //返回2个数组的交集
            $inters = array_intersect($ads, $ids);

            //合并数组并去重
            $shopIds = array_unique(array_merge($inters, $ids));
            $qs      = array_fill(0, count($shopIds), '?'); //排序用

            $shops = Shop::whereIn('shop_id', $ids)
            //->orderByRaw(DB::raw("FIELD(shop_id," . implode(',', $qs) . ")"), $shopIds)
            ->paginate(10);
             */
            //处理数据
            foreach ($shops as $key => $value) {
                $data[$key]['shop_id']       = $value->shop_id;
                $data[$key]['shop_name']     = $value->shop_name;
                $data[$key]['logo']          = $value->logo; //店铺首图
                $data[$key]['average_price'] = sprintf('%.2f', $value->average_price); //人均价
                $data[$key]['star']          = $value->score_num > 0 ? intval(($value->score / $value->score_num) * 10) / 10 : 0; //评分
                $data[$key]['industry']      = $value->industry->industries()->pluck('name'); //店铺标签
                $data[$key]['pay_bills']     = $value->tuan_order()->where('pay_status', 2)->count(); //买单人数
                $data[$key]['is_integral']   = $value->is_integral; //是否开启积分抵扣

                //是否有在线团购
                $data[$key]['tuan'] = null;
                $tuans              = Tuan::where(['shop_id' => $value->shop_id, 'type' => 1])->pluck('tuan_id');
                $tuan_info          = TuanInfo::where(['status' => 1, 'closed' => 1, 'audit' => 1])
                    ->whereIn('tuan_id', $tuans)->first();
                if ($tuan_info) {
                    $data[$key]['tuan'] = $tuan_info->title;
                }
                //是否有买单优惠
                $data[$key]['discount'] = null;
                if (count($value->shop_youhui) > 0) {
                    $data[$key]['discount'] = $value->shop_youhui->discount;
                }
                //是否有优惠券
                $data[$key]['voucher'] = null;
                $vouchers              = Tuan::where(['shop_id' => $value->shop_id, 'type' => 2])->pluck('tuan_id');
                $tuanInfo              = TuanInfo::where(['status' => 1, 'closed' => 1, 'audit' => 1])
                    ->whereIn('tuan_id', $vouchers)->first();
                if ($tuanInfo) {
                    $data[$key]['voucher'] = $tuanInfo->title;
                }
            }
            $status = 1;
            $msg    = '搜索成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }
}
